#include "selectformatwizardpage.h"
#include "ui_selectformatwizardpage.h"

#include "collectpredefinationthread.h"
#include <QRect>
#include <QVariant>
#include <QListWidgetItem>
#include <QHBoxLayout>
#include <QLayoutItem>


SelectFormatWizardPage::SelectFormatWizardPage(QWidget *parent) :
    QWizardPage(parent),
    ui(new Ui::SelectFormatWizardPage)
{
    ui->setupUi(this);

    m_btnGroup = new QButtonGroup(this);

    m_btnGroup->addButton(ui->btnCustomFormat);
    m_btnGroup->addButton(ui->btnSelectPredefined);
    m_btnGroup->setExclusive(true);

    ui->btnSelectPredefined->setChecked(true);

    m_searchThread = new CollectPredefinationThread("/home/simophin/Projects/Qt/LFCEncoder/devices",this);
    m_searchLabel = new QLabel(tr("收集预配置文件中..."),this);

    connect(m_searchThread,SIGNAL(collectFinish()),this,SLOT(onCollectFinish()));
    connect(m_searchThread,SIGNAL(collectError(int,QString)),this,SLOT(onCollectError(int,QString)));

    m_searchLabel->adjustSize();

    QRect slRect = m_searchLabel->rect();
    QRect crect = rect();

    slRect.moveCenter(crect.center());
    m_searchLabel->move(slRect.topLeft());
    m_searchLabel->setWindowFlags( Qt::FramelessWindowHint);
    m_searchLabel->setWindowModality(Qt::WindowModal);
    m_searchLabel->show();

    m_searchThread->startCollect();


    //setEnabled(false);
}

SelectFormatWizardPage::~SelectFormatWizardPage()
{
    delete ui;
}

void SelectFormatWizardPage::onCollectFinish() {
    QStringList factories;

    m_searchLabel->close();

    factories = m_searchThread->getFactoryList();

    ui->factoryList->addItems(factories);
}

void SelectFormatWizardPage::onCollectError(int, const QString &) {

}

void SelectFormatWizardPage::on_btnSelectPredefined_toggled(bool checked)
{
    emit completeChanged();
    setSelectFactoryListEnable(checked);
}

void SelectFormatWizardPage::on_factoryList_currentItemChanged(QListWidgetItem* current, QListWidgetItem* )
{
    if (!current) return;
    QString key = current->text();

    QStringList devices;
    QList<QSettings *> device_infos;
    m_searchThread->getDeviceList(key,devices,device_infos);

    ui->deviceList->clear();

    for (int i=0;i<devices.count();i++){
	QListWidgetItem *item;
	QVariant data;
	data.setValue((void *)(device_infos[i]));
	item = new QListWidgetItem(devices[i]);
	item->setData(Qt::UserRole,data);
	ui->deviceList->addItem(item);
    }
}

void SelectFormatWizardPage::setSelectFactoryListEnable(bool enable) {
    ui->deviceList->setEnabled(enable);
    ui->factoryList->setEnabled(enable);
}

void SelectFormatWizardPage::on_deviceList_currentRowChanged(int )
{
    emit completeChanged();
}

bool SelectFormatWizardPage::isComplete() const{
    return (
	    (ui->deviceList->currentItem() != NULL) ||
	    (ui->btnCustomFormat->isChecked())
	    );
}

void SelectFormatWizardPage::on_factoryList_currentRowChanged(int )
{
     emit completeChanged();
}
